package book.chapter_5;


 
import java.awt.*;       
import java.awt.event.*;    
import javax.swing.*;      
import java.io.*;         
 
public class filechooser    
{    
 
  private JFrame frm;    
  private JButton open;    
  private JButton read;    
  private JPanel p;    
  private File f;    
  private JFileChooser fc;    
  private int flag;    
 
 public filechooser()    
  {    
    frm=new JFrame("java");    
    open=new JButton("open");    
    read=new JButton("read");    
    p=new JPanel();    
    fc=new JFileChooser();    
 
 
    Container c=frm.getContentPane();    
    c.setLayout(new FlowLayout());    
 
    c.add(p);    
    p.add(open);    
    p.add(read);    
 
  
    open.addActionListener(new action());    
    read.addActionListener(new action());    
 
    frm.setSize(300,300);    
    frm.setVisible(true);    
  
    frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
  }    
 
 
private void openFile()  
         {    
               
              fc.setDialogTitle("Open File");    
 
             
         try{     
                     flag=fc.showOpenDialog(frm);     
              }    
         catch(HeadlessException head){     
 
                     System.out.println("Open File Dialog ERROR!");    
              }    
                
             
            if(flag==JFileChooser.APPROVE_OPTION)    
              {    
                    
                     f=fc.getSelectedFile();    
                     System.out.println("open file----"+f.getName());    
               }    
         }    
 
private void readFile()  
       {    
           String fileName;    
 
         
           fc.setDialogTitle("Save File");     
 
         
      try{     
                flag=fc.showSaveDialog(frm);    
           }    
      catch(HeadlessException he){    
                System.out.println("Save File Dialog ERROR!");     
           }    
 
           
         if(flag==JFileChooser.APPROVE_OPTION)    
           {    
              
                 f=fc.getSelectedFile();    
               
                 fileName=fc.getName(f);    
                
                 System.out.println(fileName);    
           }    
       }    
 

class action implements ActionListener    
  {    
    public void actionPerformed(ActionEvent e)    
      {    
 
          
        if(e.getSource()==open)    
             openFile();    
        else   
        if(e.getSource()==read)    
             readFile();    
      }    
  }    
    
} 
